import { PointObj3, Rect } from '@/types';
import { Face } from '../constants';
import { FormValue } from '../types';
import { FormInstance, FormProps, InputNumberProps } from 'antd';

export function handleLengthChange(
  lenRecord: Record<string, number>,
  record: Record<string, any[]>,
  path: string,
) {
  const target = record[path];
  if (!target) return false;
  const len = target.length;
  if (lenRecord[path] !== len) {
    lenRecord[path] = len;
    return true;
  }
  return false;
}

type PlankSize = FormValue['plank']['size'];
export function getStartPointInitialValue({
  size,
  plankFaceId,
}: {
  size: PlankSize;
  plankFaceId: Face;
}): Partial<PointObj3> {
  return {
    [Face.Top]: { z: size.thickness },
    [Face.Bottom]: { z: 0 },
    [Face.Left]: { x: 0 },
    [Face.Right]: { x: size.length },
    [Face.Front]: { y: 0 },
    [Face.Back]: { y: size.width },
  }[plankFaceId];
}
export function getEndPointInitialValue({
  size,
  plankFaceId,
  depth,
}: {
  size: PlankSize;
  plankFaceId: Face;
  depth: number;
}): Partial<PointObj3> {
  return {
    [Face.Top]: { z: size.thickness - depth },
    [Face.Bottom]: { z: 0 + depth },
    [Face.Left]: { x: 0 + depth },
    [Face.Right]: { x: size.length - depth },
    [Face.Front]: { y: 0 + depth },
    [Face.Back]: { y: size.width - depth },
  }[plankFaceId];
}

export type LimitValue = Pick<InputNumberProps<number>, 'min' | 'max'>;
type PointLimitValue = Partial<Record<keyof PointObj3, LimitValue>>;
export function getEndPointLimitValue({
  size,
  plankFaceId,
}: {
  size: PlankSize;
  plankFaceId: Face;
}): PointLimitValue {
  return {
    [Face.Top]: { z: { min: 0 } },
    [Face.Bottom]: { z: { max: size.thickness } },
    [Face.Left]: { x: { max: size.length } },
    [Face.Right]: { x: { min: 0 } },
    [Face.Front]: { y: { max: size.width } },
    [Face.Back]: { y: { min: 0 } },
  }[plankFaceId];
}
export function getDepthLimitValue({
  size,
  plankFaceId,
}: {
  size: PlankSize;
  plankFaceId: Face;
}): LimitValue {
  return {
    [Face.Top]: { max: size.thickness },
    [Face.Bottom]: { max: size.thickness },
    [Face.Left]: { max: size.length },
    [Face.Right]: { max: size.length },
    [Face.Front]: { max: size.width },
    [Face.Back]: { max: size.width },
  }[plankFaceId];
}
export function getRadiusLimitValue({ rect }: { rect: Rect }): LimitValue {
  const maxRadius = Math.min(rect.width, rect.height) / 4;
  return { max: maxRadius };
}

export function formHasError(form: FormInstance) {
  return form
    .validateFields()
    .then(() => false)
    .catch((error) => error.errorFields.length > 0);
}
